/*
 * @lc app=leetcode.cn id=112 lang=cpp
 *
 * [112] 路径总和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

// struct TreeNode
// {
//   int val;
//   TreeNode* left;
//   TreeNode* right;
//   TreeNode(int x) : val(x), left(NULL), right(NULL) {}
// };

class Solution
{
 public:
  bool hasPathSum(TreeNode* root, int sum)
  {
    if (nullptr == root) return false;

    if (nullptr == root->left && nullptr == root->right)  // 遍历到叶子结点
    {
      return root->val == sum;  // root不断被左右子树递归取代，sum不断被newsum递归取代
    }

    int newsum = sum - root->val;
    return hasPathSum(root->left, newsum) || hasPathSum(root->right, newsum);
  }
};
// @lc code=end
